﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace DC.DCHierarchy.DCResolvers
{
    class Program
    {
        static void Main(string[] args)
        {
            //在宿主端安装数据契约解析器
            using (ServiceHost host = new ServiceHost(typeof(MyServices), new Uri("net.tcp://192.168.3.44:8001/")))
            {
                if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    host.Description.Behaviors.Add(behavior);
                }

                host.AddServiceEndpoint(typeof(IContract), new NetTcpBinding(), "");
                host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

                //Step1. 遍历host.Description.Endpoints集合
                foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
                {
                    //Step2. 遍历每个Endpoint中的Operations集合
                    foreach (OperationDescription operation in endpoint.Contract.Operations)
                    {
                        //Step3. 在operation的Behaviors集合中找到一个称为DataContractSerializerOperationBehavior的行为
                        DataContractSerializerOperationBehavior behavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
                        //设置自定义数据契约解析器
                        behavior.DataContractResolver = new CustomDataContractResolver();
                    }
                }

                host.Open();
                Console.WriteLine("Host has been started");
                Console.ReadKey();
                host.Close();
            }
        }
    }
}
